package com.assic.utils.web.tag;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.nutz.log.Log;
import org.nutz.log.Logs;

/**
 * 
 * @author Kerbores 自定义集合迭代器 View里的对象操作无外乎就是2种 1：单独对象，我们可以直接获取对象及其属性进行展示
 *         2：集合对象，我们可以使用本类提供的标签进行迭代即可
 */
@SuppressWarnings("rawtypes")
public class IteratorTag extends BodyTagSupport {

	/**
	 * 序列号版本号
	 */
	private static final long serialVersionUID = 1L;
	protected static final Log logger = Logs.getLog(IteratorTag.class);

	private String name;
	private Iterator item;
	private String type;

	// FIX @ 2014-01-11 11:56:00 set Object to iterator is better
	public void setCollection(Object collection) {
		item = null;
		Collection c = null;
		// 根据传入的对象判断决定是否为集合赋值
		if (collection instanceof Collection) {
			c = (Collection) collection;
		}
		// 未赋值，说明参数对象不是可迭代集合
		if (c == null) {
			c = new ArrayList<>();
			c.add(null);
			item = c.iterator();
			logger.error("非集合对象不能进行迭代");
		} else if (c.size() > 0) {
			item = c.iterator();
		} else if (c.size() == 0) {
			c = new ArrayList<>();
			c.add(null);
			item = c.iterator();
			logger.error("空集合对象不能进行迭代");
		} else {
			item = new ArrayList().iterator();
			// logger.error("非集合对象不能进行迭代");
			logger.error("空集合对象不能进行迭代");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "IteratorTag [name=" + name + ", item=" + item + ", type="
				+ type + "]";
	}

	public int doStartTag() {
		if (item == null) {
			return SKIP_BODY;
		} else {
			return continueNext(item);
		}
	}

	@SuppressWarnings("deprecation")
	private int continueNext(Iterator item2) {
		if (item2.hasNext()) {
			Object object = item2.next();
			if (object != null) {
				pageContext.setAttribute(name, object, PageContext.PAGE_SCOPE);
			}
			return EVAL_BODY_TAG;
		}
		return SKIP_BODY;
	}

	public int doAfterBody() {
		return continueNext(item);
	}

	public int doEndTag() {
		try {
			if (bodyContent != null) {
				bodyContent.writeOut(bodyContent.getEnclosingWriter());
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return EVAL_PAGE;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Iterator getItem() {
		return item;
	}

	public void setItem(Iterator item) {
		this.item = item;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
